﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class SysManage_RolesM_BWebColumn : INTPage
{
    SqlHelp help = new SqlHelp();
    public int rowNo = 0;
    CommonMethod comHelp = new CommonMethod();

    protected void Page_Load(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);
        if (!IsPostBack)
        { WebsBind(Session["UserCode"].ToString()); }        
    }

    #region 初始化绑定列表数据 WebsBind(string UserCode)
    protected void WebsBind(string UserCode)
    {   
        // 页面权限
        comHelp.GetRight(this, new string[] { Session["UserCode"].ToString(), Session["CoCode"].ToString(), "webColumn" }, 
            GrvColumns, new string[] { "cmdAdd", "cmdEdit" }, new int[] { GrvColumns.Columns.Count-2, GrvColumns.Columns.Count-1 }, "../../SLogin.aspx");
        // 数据绑定
        QueryBind(0);
        //
        TableNameBind();
    }
    #endregion

    public void TableNameBind()
    {
        ddlTableName.DataSource = help.GetDataTable("select distinct BelongToTableName from B_Roles_Column");
        ddlTableName.DataValueField = "BelongToTableName";
        ddlTableName.DataTextField = "BelongToTableName";
        ddlTableName.DataBind();
        ddlTableName.Items.Insert(0, new ListItem("请选择(Please Select)", "-1"));
    }

    #region GridView 行事件
    // GridView换页
    protected void GrvColumns_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            GrvColumns.PageIndex = e.NewPageIndex;
            QueryBind(Convert.ToInt16(HidQueryFlag.Value.ToString()));
        }
        catch
        { }
    }

    //行删除
    protected void GrvColumns_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl2);

        string ColumnType = GrvColumns.Rows[e.RowIndex].Cells[1].Text.Trim().ToString();
        int ComN = Convert.ToInt16(help.RunSqlInt(string.Format("select count(*) from B_RolesGroupAndColumn  where ColumnType='{0}'", ColumnType)));
        if (ComN < 1)
        {
            string StrDelete = string.Format(" Delete from B_Roles_Column where ColumnType='{0}'", ColumnType);
            if (help.RunSqlInt(StrDelete) > 0)
            {
                CommonMethod.regAlertMessage("删除成功！", this);
                QueryBind(Convert.ToInt16(HidQueryFlag.Value.ToString()));
            }
        }
        else
        {
            CommonMethod.regAlertMessage(ColumnType + "  此字段存在于页面角色组，现在不可以删除，要删除请先到页面角色组管理删除此字段！", this);
        }

    }
    //行编辑
    protected void GrvColumns_SelectedIndexChanged(object sender, EventArgs e)
    {
        TxtColumnType.Text = GrvColumns.Rows[GrvColumns.SelectedIndex].Cells[1].Text.Trim().ToString();
        TxtColumnType.Enabled = false;
        TxtColumnName.Text = GrvColumns.Rows[GrvColumns.SelectedIndex].Cells[2].Text.Trim().ToString();
        txtColumnWidth.Text = GrvColumns.Rows[GrvColumns.SelectedIndex].Cells[3].Text.Trim().ToString();
        txtColumnPosition.Text = GrvColumns.Rows[GrvColumns.SelectedIndex].Cells[4].Text.Trim().ToString();
        TxtColumnDesc.Text = GrvColumns.DataKeys[GrvColumns.SelectedIndex]["ColumnDesc"].ToString();
        //GrvColumns.Rows[GrvColumns.SelectedIndex].Cells[5].Text.Trim().ToString();
        ddlTableName.SelectedValue = GrvColumns.Rows[GrvColumns.SelectedIndex].Cells[6].Text.Trim().ToString();

        ddlReaptFlag.SelectedValue = GrvColumns.DataKeys[GrvColumns.SelectedIndex]["ReaptFlagValue"].ToString();

        ddlTimeStyle.SelectedValue = GrvColumns.Rows[GrvColumns.SelectedIndex].Cells[8].Text.Trim().ToString();
        
        radDataFromScala.SelectedValue = GrvColumns.DataKeys[GrvColumns.SelectedIndex]["DataFromScalaFlag"].ToString();
        radDropDownListName.SelectedValue = GrvColumns.DataKeys[GrvColumns.SelectedIndex]["DropDownListNameFlag"].ToString();

        cmdAdd.Enabled = false;
        cmdEdit.Enabled = true;
    }
    #endregion

    //Gridview 行事件
    protected void GrvColumns_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        rowNo++;
        //鼠标经过事件
        if (e.Row.RowIndex != -1)
        {
            //设置悬浮鼠标指针形状为"小手"
            e.Row.Attributes["style"] = "Cursor:hand";
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "lastColor=this.style.backgroundColor;this.style.backgroundColor='#CCCC99';");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=lastColor;");
                ((LinkButton)e.Row.Cells[GrvColumns.Columns.Count - 1].Controls[0]).Attributes.Add("onclick", "return confirm('确实要删除？');");
            }
        }
    }

    #region 查询
    protected void cmdQuery_Click(object sender, EventArgs e)
    {
        QueryBind(1);
        HidQueryFlag.Value = "1";
    }
    //
    protected void QueryBind(int n)
    {
        string StrSql = " select  RC.ColumnPosition,RC.ColumnType,RC.ColumnName,RC.ColumnWidth,RC.BelongToTableName,RC.ColumnDesc,"
            + " case RC.RepeatFlag when '1' then 'Repeat' else 'Not Repeat' end RepeatFlag,isnull(RepeatFlag,0) ReaptFlagValue,"
            + " RC.ColumnTimeStyle,case RC.DataFromScalaFlag when 0 then '否' when 1 then '是' end DataFromScalaFlagShow ,DataFromScalaFlag, "
            + " case RC.DropDownListNameFlag when 1 then '是' else '否' end DropDownListNameFlagShow,DropDownListNameFlag "
            + " from B_Roles_Column RC where DeleteFlag<>1";

        if (n == 1)
        {
            if (!string.IsNullOrEmpty(TxtColumnType.Text.ToString()))
            {
                StrSql += string.Format(" and RC.ColumnType like '%{0}%'", TxtColumnType.Text.ToString());
            }
            if (!string.IsNullOrEmpty(TxtColumnName.Text.ToString()))
            {
                StrSql += string.Format(" and RC.ColumnName like '%{0}%'", TxtColumnName.Text.ToString());
            }
            if (!string.IsNullOrEmpty(TxtColumnDesc.Text.ToString()))
            {
                StrSql += string.Format(" and RC.ColumnDesc like '%{0}%'", TxtColumnDesc.Text.ToString());
            }
            if (!ddlTableName.SelectedValue.Equals("-1"))
            {
                StrSql += string.Format(" and RC.BelongToTableName='{0}'", ddlTableName.SelectedValue.ToString());
            }
        }

        StrSql += " order by RC.ColumnPosition ";

        DataTable Dt = help.GetDataTable(StrSql);
        GrvColumns.DataSource = Dt;
        GrvColumns.DataBind();
        // 显示页码信息
        if (Dt.Rows.Count > 0)
        {
            // 设置分页行永远显示
            GrvColumns.BottomPagerRow.Visible = true;
            //赋值Label记录条数
            Label label1 = GrvColumns.BottomPagerRow.FindControl("lblCount") as Label;
            label1.Text = Dt.Rows.Count.ToString();
        }
    }
    #endregion

    #region 添加
    protected void cmdAdd_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);
        //统计列表中与要添加的类型相同的个数
        int ComN = 0;
        //
        string StrGvNSql = "select count(*) from B_Roles_Column where ColumnType='" + TxtColumnType.Text.ToString() + "'";
        ComN = Convert.ToInt16(help.RunSqlReturn(StrGvNSql));
        if (ComN < 1)
        {
            //获取当前用户名称
            string UserName = Session["UserCode"].ToString();
            //当前时间
            string StrDate = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");

            string StrInsert = string.Format("Insert Into B_Roles_Column(ColumnPosition,ColumnType,ColumnName,"
                + "ColumnWidth,ColumnDesc,DeleteFlag,AddAuthor,AddDate,UpdateAuthor,UpdateDate,BelongToTableName,"
                + "RepeatFlag,ColumnTimeStyle,DataFromScalaFlag,DropDownListNameFlag) "
                + "Values({8},'{0}','{1}','{2}','{3}',0,'{4}','{5}','{6}','{7}','{9}','{10}','{11}','{12}',{13})",
                TxtColumnType.Text.ToString(), TxtColumnName.Text.ToString(), txtColumnWidth.Text.ToString(), TxtColumnDesc.Text.ToString(),
                UserName, StrDate, UserName, StrDate, txtColumnPosition.Text.ToString(), ddlTableName.SelectedItem.Text.ToString(),
                ddlReaptFlag.SelectedValue.ToString(), ddlTimeStyle.SelectedValue, radDataFromScala.SelectedValue, radDropDownListName.SelectedValue);
            //添加结果标志
            int result = help.RunSqlInt(StrInsert);
            if (result > 0)
            {
                UpdateForRepeatFlag();
                CommonMethod.regAlertMessage("操作成功-Success!", this);
                QueryBind(1);
                HidQueryFlag.Value = "0";
                SetFlag(true);
                TxtColumnType.Focus();
            }
            else
            {
                CommonMethod.regAlertMessage("出现错误-Error!", this);
                TxtColumnType.Focus();
            }
        }
        else { CommonMethod.regAlertMessage(TxtColumnType.Text.ToString() + "  已经存在！", this); }
    }
    #endregion

    #region 编辑
    protected void cmdEdit_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCodeAndCoCode(this, CommonModel.errorTimeOutUrl2);
        string StrUpdate = string.Format(" Update B_Roles_Column set ColumnPosition={4},ColumnName='{0}',ColumnWidth='{1}',"
            + "ColumnDesc='{2}',RepeatFlag='{5}',BelongToTableName='{6}',ColumnTimeStyle='{7}',DataFromScalaFlag='{8}',"
            + " DropDownListNameFlag={9} where ColumnType='{3}' ",
            TxtColumnName.Text.ToString(), txtColumnWidth.Text.ToString(), TxtColumnDesc.Text.ToString(),
            TxtColumnType.Text.ToString(), txtColumnPosition.Text.ToString(), ddlReaptFlag.SelectedValue.ToString(),
            ddlTableName.SelectedItem.Text.ToString(), ddlTimeStyle.SelectedValue, radDataFromScala.SelectedValue,
            radDropDownListName.SelectedValue);
        if (help.RunSqlInt(StrUpdate) > 0)
        {
            UpdateForRepeatFlag();
            CommonMethod.regAlertMessage("更新成功！", this);
            QueryBind(1);
            HidQueryFlag.Value = "0";

            SetFlag(true);
        }
        else
        {
            CommonMethod.regAlertMessage("更新失败！", this);
        }
    }
    #endregion

    //重置
    protected void cmdClear_ServerClick(object sender, EventArgs e)
    {
        SetFlag(true);
    }
    public void SetFlag(bool flag)
    {
        cmdAdd.Enabled = flag;
        cmdEdit.Enabled = !flag;
        TxtColumnType.Enabled = flag;
        TxtColumnType.Text = "";
        txtColumnPosition.Text = "";
        txtColumnWidth.Text = "";
        TxtColumnName.Text = "";
        TxtColumnDesc.Text = "";
        ddlTimeStyle.SelectedIndex = 0;
        radDataFromScala.SelectedIndex = 0;
        radDropDownListName.SelectedIndex = 0;
    }
    
    //跳页
    protected void GrvColumns_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "NewPage")
            {
                TextBox tb = GrvColumns.BottomPagerRow.FindControl("txtNewPageIndex") as TextBox;
                int pageindex = Convert.ToInt32(tb.Text);
                GrvColumns.PageIndex = pageindex - 1;
                //数据绑定
                QueryBind(Convert.ToInt16(HidQueryFlag.Value.ToString()));
            }
        }
        catch
        {
            CommonMethod.regAlertMessage("输入不合法-Error format!", this);
        }
    }

    public void UpdateForRepeatFlag()
    {
        DataTable dt = help.GetDataTable("select ColumnDesc from B_Roles_Column where RepeatFlag=1 ");
        string temp = string.Empty;
        foreach (DataRow row in dt.Rows)
        {
            temp += "/" + row["ColumnDesc"].ToString() + "/";
        }
        help.RunSqlInt(string.Format("update B_Roles_Column set ForRepeatFlag=1 where patindex('%/'+ColumnType+'/%','{0}')>0", temp));
    }
}